import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

/**
 * 营销中心仓库：优惠券、促销方案、发放记录
 * - localStorage 持久化
 * - 提供基础 CRUD / 启停 / 筛选 / 发券
 */
export const useMarketingStore = defineStore('marketing', () => {
  // 本地持久化键
  const COUPONS_KEY = 'erppos_coupons'
  const PROMOTIONS_KEY = 'erppos_promotions'
  const ISSUED_KEY = 'erppos_coupon_issued'

  // 状态
  const couponList = ref([])
  const promotionList = ref([])
  const issuedRecords = ref([]) // 发放记录：{ id, couponId, couponName, memberId, memberName, phone, quantity, date, operator }

  // 统计
  const totalActiveCoupons = computed(() => couponList.value.filter(c => c.status === 'active').length)
  const totalActivePromotions = computed(() => promotionList.value.filter(p => p.status === 'active').length)

  // 初始化：从 localStorage 读取或写入示例数据
  const initializeMarketingData = () => {
    const cachedCoupons = localStorage.getItem(COUPONS_KEY)
    const cachedPromotions = localStorage.getItem(PROMOTIONS_KEY)
    const cachedIssued = localStorage.getItem(ISSUED_KEY)
    if (cachedCoupons) couponList.value = JSON.parse(cachedCoupons)
    if (cachedPromotions) promotionList.value = JSON.parse(cachedPromotions)
    if (cachedIssued) issuedRecords.value = JSON.parse(cachedIssued)

    if (!cachedCoupons) {
      couponList.value = [
        {
          id: 'C001',
          name: '新客立减5元',
          type: 'amount', // amount | percent
          value: 5,
          minSpend: 30,
          validFrom: '2024-05-01',
          validTo: '2024-06-30',
          channels: ['pos', 'online'], // pos | online
          total: 1000,
          issued: 120,
          used: 50,
          status: 'active', // active | inactive
          description: '到店/线上均可使用，满30-5'
        },
        {
          id: 'C002',
          name: '夏日9折券',
          type: 'percent',
          value: 90, // 90 表示 9 折
          minSpend: 0,
          validFrom: '2024-06-01',
          validTo: '2024-08-31',
          channels: ['pos'],
          total: 500,
          issued: 60,
          used: 12,
          status: 'inactive',
          description: 'POS 端使用，不与满减同享'
        },
      ]
    }

    if (!cachedPromotions) {
      promotionList.value = [
        {
          id: 'P001',
          name: '满100减20',
          ruleType: 'fullReduction', // fullReduction | discount | buyXGetY
          ruleConfig: { threshold: 100, discount: 20 },
          scopeType: 'all', // all | category
          categories: [],
          validFrom: '2024-05-01',
          validTo: '2024-12-31',
          status: 'active',
          description: '全场通用满减'
        },
        {
          id: 'P002',
          name: '日用品 95 折',
          ruleType: 'discount',
          ruleConfig: { percent: 95 }, // 95 表示 9.5 折
          scopeType: 'category',
          categories: ['日用品'],
          validFrom: '2024-06-01',
          validTo: '2024-09-30',
          status: 'inactive',
          description: '仅日用品分类参与折扣'
        },
      ]
    }

    if (!cachedIssued) {
      issuedRecords.value = [
        // 示例发放记录
        { id: 'I001', couponId: 'C001', couponName: '新客立减5元', memberId: 'M001', memberName: '王芳', phone: '13800000001', quantity: 1, date: '2024-05-10T10:20:00Z', operator: '系统' },
      ]
    }

    persistAll()
  }

  const persistAll = () => {
    localStorage.setItem(COUPONS_KEY, JSON.stringify(couponList.value))
    localStorage.setItem(PROMOTIONS_KEY, JSON.stringify(promotionList.value))
    localStorage.setItem(ISSUED_KEY, JSON.stringify(issuedRecords.value))
  }

  // 通用工具
  const formatDateString = (d) => {
    if (!d) return ''
    try {
      const date = new Date(d)
      if (Number.isNaN(date.getTime())) return String(d)
      return date.toISOString().slice(0, 10)
    } catch {
      return String(d)
    }
  }

  // ========== 优惠券 ========== //
  const getFilteredCoupons = (filters = {}) => {
    return couponList.value.filter(c => {
      if (filters.search) {
        const s = String(filters.search).toLowerCase()
        if (!c.name.toLowerCase().includes(s)) return false
      }
      if (filters.status && filters.status !== 'all' && c.status !== filters.status) return false
      return true
    })
  }

  const addCoupon = (data) => {
    const now = new Date().toISOString()
    const item = {
      id: 'C' + Date.now(),
      name: data.name,
      type: data.type || 'amount',
      value: Number(data.value || 0),
      minSpend: Number(data.minSpend || 0),
      validFrom: formatDateString(data.validFrom || (data.validRange?.[0] || '')),
      validTo: formatDateString(data.validTo || (data.validRange?.[1] || '')),
      channels: Array.isArray(data.channels) ? [...data.channels] : [],
      total: Number(data.total || 0),
      issued: Number(data.issued || 0),
      used: Number(data.used || 0),
      status: data.status || 'inactive',
      description: data.description || '',
      createdAt: now,
      updatedAt: now,
    }
    couponList.value.unshift(item)
    persistAll()
    return item
  }

  const updateCoupon = (id, updates) => {
    const idx = couponList.value.findIndex(x => x.id === id)
    if (idx === -1) return null
    const merged = {
      ...couponList.value[idx],
      ...updates,
      validFrom: formatDateString(updates.validFrom || updates.validRange?.[0] || couponList.value[idx].validFrom),
      validTo: formatDateString(updates.validTo || updates.validRange?.[1] || couponList.value[idx].validTo),
      updatedAt: new Date().toISOString(),
    }
    couponList.value[idx] = merged
    persistAll()
    return merged
  }

  const deleteCoupon = (id) => {
    const idx = couponList.value.findIndex(x => x.id === id)
    if (idx === -1) return false
    couponList.value.splice(idx, 1)
    // 删除相关发放记录
    issuedRecords.value = issuedRecords.value.filter(r => r.couponId !== id)
    persistAll()
    return true
  }

  const toggleCouponStatus = (id) => {
    const c = couponList.value.find(x => x.id === id)
    if (!c) return null
    c.status = c.status === 'active' ? 'inactive' : 'active'
    c.updatedAt = new Date().toISOString()
    persistAll()
    return c.status
  }

  const issueCoupon = (couponId, member, quantity = 1, operator = '系统') => {
    const c = couponList.value.find(x => x.id === couponId)
    if (!c) return { ok: false, message: '优惠券不存在' }
    if (c.status !== 'active') return { ok: false, message: '优惠券未启用' }
    if (quantity <= 0) return { ok: false, message: '数量需大于0' }

    // 简单判断剩余可发放量
    const remaining = Math.max(0, Number(c.total || 0) - Number(c.issued || 0))
    if (remaining < quantity) return { ok: false, message: '发放数量超过配额' }

    const record = {
      id: 'I' + Date.now(),
      couponId: c.id,
      couponName: c.name,
      memberId: member?.id || '',
      memberName: member?.name || '',
      phone: member?.phone || '',
      quantity: Number(quantity || 1),
      date: new Date().toISOString(),
      operator,
    }
    issuedRecords.value.unshift(record)
    c.issued = Number(c.issued || 0) + Number(quantity || 1)
    persistAll()
    return { ok: true, record }
  }

  const getIssuedRecordsByCoupon = (couponId) => issuedRecords.value.filter(r => r.couponId === couponId)

  // ========== 促销方案 ========== //
  const getFilteredPromotions = (filters = {}) => {
    return promotionList.value.filter(p => {
      if (filters.search) {
        const s = String(filters.search).toLowerCase()
        if (!p.name.toLowerCase().includes(s)) return false
      }
      if (filters.status && filters.status !== 'all' && p.status !== filters.status) return false
      return true
    })
  }

  const addPromotion = (data) => {
    const now = new Date().toISOString()
    const item = {
      id: 'P' + Date.now(),
      name: data.name,
      ruleType: data.ruleType || 'fullReduction',
      ruleConfig: { ...(data.ruleConfig || {}) },
      scopeType: data.scopeType || 'all',
      categories: Array.isArray(data.categories) ? [...data.categories] : [],
      validFrom: formatDateString(data.validFrom || (data.validRange?.[0] || '')),
      validTo: formatDateString(data.validTo || (data.validRange?.[1] || '')),
      status: data.status || 'inactive',
      description: data.description || '',
      createdAt: now,
      updatedAt: now,
    }
    promotionList.value.unshift(item)
    persistAll()
    return item
  }

  const updatePromotion = (id, updates) => {
    const idx = promotionList.value.findIndex(x => x.id === id)
    if (idx === -1) return null
    const merged = {
      ...promotionList.value[idx],
      ...updates,
      ruleConfig: { ...promotionList.value[idx].ruleConfig, ...(updates.ruleConfig || {}) },
      validFrom: formatDateString(updates.validFrom || updates.validRange?.[0] || promotionList.value[idx].validFrom),
      validTo: formatDateString(updates.validTo || updates.validRange?.[1] || promotionList.value[idx].validTo),
      updatedAt: new Date().toISOString(),
    }
    promotionList.value[idx] = merged
    persistAll()
    return merged
  }

  const deletePromotion = (id) => {
    const idx = promotionList.value.findIndex(x => x.id === id)
    if (idx === -1) return false
    promotionList.value.splice(idx, 1)
    persistAll()
    return true
  }

  const togglePromotionStatus = (id) => {
    const p = promotionList.value.find(x => x.id === id)
    if (!p) return null
    p.status = p.status === 'active' ? 'inactive' : 'active'
    p.updatedAt = new Date().toISOString()
    persistAll()
    return p.status
  }

  // 导出 CSV（可选）
  const exportCouponsToCSV = (list = null) => {
    const rows = (list || couponList.value).map(c => [
      c.name,
      c.type === 'amount' ? '满减券' : '折扣券',
      c.type === 'amount' ? `¥${c.value}` : `${(Number(c.value) / 10).toFixed(1)}折`,
      c.minSpend > 0 ? `满¥${c.minSpend}` : '无门槛',
      `${c.validFrom} ~ ${c.validTo}`,
      (c.channels || []).join('/'),
      `${c.issued}/${c.total}`,
      c.used || 0,
      c.status,
    ])
    const headers = ['名称', '类型', '面值', '门槛', '有效期', '渠道', '已发/配额', '已用', '状态']
    const csv = [headers.join(','), ...rows.map(r => r.join(','))].join('\n')
    const blob = new Blob(['\ufeff' + csv], { type: 'text/csv;charset=utf-8;' })
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    link.href = url
    link.download = `优惠券_${new Date().toISOString().slice(0,10)}.csv`
    link.click()
    URL.revokeObjectURL(url)
  }

  const exportPromotionsToCSV = (list = null) => {
    const rows = (list || promotionList.value).map(p => [
      p.name,
      p.ruleType,
      JSON.stringify(p.ruleConfig || {}),
      p.scopeType === 'all' ? '全场' : `分类:${(p.categories || []).join('/')}`,
      `${p.validFrom} ~ ${p.validTo}`,
      p.status,
    ])
    const headers = ['名称', '规则类型', '规则参数', '适用范围', '有效期', '状态']
    const csv = [headers.join(','), ...rows.map(r => r.join(','))].join('\n')
    const blob = new Blob(['\ufeff' + csv], { type: 'text/csv;charset=utf-8;' })
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    link.href = url
    link.download = `促销_${new Date().toISOString().slice(0,10)}.csv`
    link.click()
    URL.revokeObjectURL(url)
  }

  return {
    // state
    couponList,
    promotionList,
    issuedRecords,

    // stats
    totalActiveCoupons,
    totalActivePromotions,

    // init
    initializeMarketingData,

    // coupons
    getFilteredCoupons,
    addCoupon,
    updateCoupon,
    deleteCoupon,
    toggleCouponStatus,
    issueCoupon,
    getIssuedRecordsByCoupon,
    exportCouponsToCSV,

    // promotions
    getFilteredPromotions,
    addPromotion,
    updatePromotion,
    deletePromotion,
    togglePromotionStatus,
    exportPromotionsToCSV,
  }
})


